package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpChatService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpChat;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import me.chanjar.weixin.cp.bean.message.WxCpAppChatMessage;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 发送消息到群聊会话
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "发送消息到群聊会话")
@RestController("workWxChatController")
@RequestMapping("/weChat/auth/workWx/chat")
public class WorkWxChatController extends BaseController {

    /**
     * 创建群聊会话
     *
     * @param name    群聊名，最多50个utf8字符，超过将截断
     * @param owner   指定群主的id。如果不指定，系统会随机从userlist中选一人作为群主
     * @param users
     * @param chatId
     * @param request
     * @return
     */
    @ApiOperation("创建群聊会话")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = "群聊名，最多50个utf8字符，超过将截断", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "owner", value = "指定群主的id。如果不指定，系统会随机从userlist中选一人作为群主", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "users", value = "群成员id列表。至少2人，至多500人", required = true, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊的唯一标志", required = false, dataType = "String")
    })
    @PostMapping(value = "/create")
    public Result<String> create(String name, String owner, List<String> users, String chatId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        try {
            String s = chatService.create(name, owner, users, chatId);
            return getResult(s);
        } catch (WxErrorException e) {
            log.error("创建群聊会话出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 修改群聊会话
     *
     * @param chatId        群聊id
     * @param name          新的群聊名
     * @param owner         新群主的id
     * @param usersToAdd    添加成员的id列表
     * @param usersToDelete 踢出成员的id列表
     * @param request
     * @return
     */
    @ApiOperation("修改群聊会话")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "新的群聊名", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "owner", value = "新群主的id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "usersToAdd", value = "添加成员的id列表", required = false, dataType = "List"),
            @ApiImplicitParam(paramType = "query", name = "usersToDelete", value = "踢出成员的id列表", required = false, dataType = "List"),
    })
    @PostMapping(value = "/update")
    public Result<String> update(String chatId, String name, String owner, List<String> usersToAdd, List<String> usersToDelete, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        try {
            chatService.update(chatId, name, owner, usersToAdd, usersToDelete);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("修改群聊会话出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取群聊会话
     *
     * @param chatId  群聊id
     * @param request
     * @return
     */
    @ApiOperation("获取群聊会话")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String")
    })
    @GetMapping(value = "/update")
    public Result<WxCpChat> update(String chatId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        try {
            WxCpChat wxCpChat = chatService.get(chatId);
            return getResult(wxCpChat);
        } catch (WxErrorException e) {
            log.error("获取群聊会话出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }


    /**
     * 应用推送消息-文本
     *
     * @param chatId  群聊id
     * @param content 消息内容
     * @param safe    表示是否是保密消息，0表示否，1表示是
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-文本")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "content", value = "消息内容", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "safe", value = "表示是否是保密消息，0表示否，1表示是", required = true, dataType = "boolean")
    })
    @PostMapping(value = "/sendText")
    public Result<String> sendText(String chatId, String content, boolean safe, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage appChatMessage = WxCpAppChatMessage.buildTextMsg(chatId, content, safe);
        try {
            chatService.sendMsg(appChatMessage);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-文本出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }


    /**
     * 应用推送消息-图片
     *
     * @param chatId  群聊id
     * @param mediaId 图片媒体文件id
     * @param safe    表示是否是保密消息，0表示否，1表示是
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "图片媒体文件id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "safe", value = "表示是否是保密消息，0表示否，1表示是", required = true, dataType = "boolean")
    })
    @PostMapping(value = "/sendImg")
    public Result<String> sendImg(String chatId, String mediaId, boolean safe, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("image");
        messageBuilder.chatId(chatId);
        messageBuilder.mediaId(mediaId);
        messageBuilder.safe(safe);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-图片出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-语音
     *
     * @param chatId  群聊id
     * @param mediaId 语音文件id
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-语音")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "语音文件id", required = true, dataType = "String")
    })
    @PostMapping(value = "/sendVoice")
    public Result<String> sendVoice(String chatId, String mediaId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("voice");
        messageBuilder.chatId(chatId);
        messageBuilder.mediaId(mediaId);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-语音出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-视频
     *
     * @param chatId      群聊id
     * @param mediaId     语音文件id
     * @param title       视频消息的标题
     * @param description 视频消息的描述
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-视频")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "媒体文件id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "title", value = "视频消息的标题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "视频消息的描述", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "safe", value = "表示是否是保密消息，0表示否，1表示是", required = true, dataType = "boolean")
    })
    @PostMapping(value = "/sendVideo")
    public Result<String> sendVideo(String chatId, String mediaId, String title, String description, boolean safe, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("video");
        messageBuilder.chatId(chatId);
        messageBuilder.mediaId(mediaId);
        messageBuilder.title(title);
        messageBuilder.description(description);
        messageBuilder.safe(safe);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-视频出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-文件
     *
     * @param chatId  群聊id
     * @param mediaId 语音文件id
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "媒体文件id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "safe", value = "表示是否是保密消息，0表示否，1表示是", required = true, dataType = "boolean")
    })
    @PostMapping(value = "/sendFile")
    public Result<String> sendFile(String chatId, String mediaId, boolean safe, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("file");
        messageBuilder.chatId(chatId);
        messageBuilder.mediaId(mediaId);
        messageBuilder.safe(safe);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-文件出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-文本卡片
     *
     * @param chatId      群聊id
     * @param mediaId     媒体文件id
     * @param title       标题
     * @param description 描述
     * @param url         点击后跳转的链接
     * @param btntxt      按钮文字
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-文本卡片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "媒体文件id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "title", value = "标题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "描述", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "url", value = "点击后跳转的链接", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "btntxt", value = "按钮文字", required = true, dataType = "String")
    })
    @PostMapping(value = "/sendTextCard")
    public Result<String> sendTextCard(String chatId, String mediaId, String title, String description, String url, String btntxt, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("textcard");
        messageBuilder.chatId(chatId);
        messageBuilder.mediaId(mediaId);
        messageBuilder.title(title);
        messageBuilder.description(description);
        messageBuilder.url(url);
        messageBuilder.btnTxt(btntxt);

        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-文本卡片出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-图文
     *
     * @param chatId      群聊id
     * @param title       标题
     * @param description 描述
     * @param url         点击后跳转的链接
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-图文")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "articles", value = "图文消息", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "title", value = "标题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "描述", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "url", value = "点击后跳转的链接", required = true, dataType = "String")
    })
    @PostMapping(value = "/sendNews")
    public Result<String> sendNews(String chatId, List<NewArticle> articles, String title, String description, String url, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("news");
        messageBuilder.chatId(chatId);
        messageBuilder.articles(articles);
        messageBuilder.title(title);
        messageBuilder.description(description);
        messageBuilder.url(url);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-图文出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-企业图文
     *
     * @param chatId  群聊id
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-企业图文")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mediaId", value = "媒体文件id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "articles", value = "图文消息", required = true, dataType = "List")
    })
    @PostMapping(value = "/sendMpNews")
    public Result<String> sendMpNews(String chatId, List<MpnewsArticle> articles, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("mpnews");
        messageBuilder.chatId(chatId);
        messageBuilder.mpnewsArticles(articles);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-企业图文出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 应用推送消息-Markdown
     *
     * @param chatId  群聊id
     * @param request
     * @return
     */
    @ApiOperation("应用推送消息-Markdown")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "chatId", value = "群聊id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "content", value = "内容", required = true, dataType = "String")
    })
    @PostMapping(value = "/sendMarkdowns")
    public Result<String> sendMarkdowns(String chatId, String content, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpChatService chatService = wxCpService.getChatService();

        // 构建应用消息
        WxCpAppChatMessage.WxCpAppChatMessageBuilder messageBuilder = WxCpAppChatMessage.builder();
        messageBuilder.msgType("markdown");
        messageBuilder.chatId(chatId);
        messageBuilder.content(content);
        try {
            chatService.sendMsg(messageBuilder.build());
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("应用推送消息-Markdown出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }
}
